package com.nahuobao.common;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * Created by youkun on 2018/1/26.
 */
public class FileUploadUtil {

    /**
     * 创建文件
     * @param file
     * @param path
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file, String path) throws Exception{
        if(file==null){
            throw new Exception("file is null");
        }
        if(path==null){
            throw new Exception("file path is null");
        }
        //获取文件的后缀名
        String fileName = file.getOriginalFilename();
        String suffix = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        String filePath = path+"/"+suffix;
        File f = new File(path,suffix);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }else{
            f.createNewFile();
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        return suffix;
    }

    /**
     * 删除文件
     * @param path
     * @return
     * @throws Exception
     */
    public static String deleteFile(String path) throws Exception{
        if(path==null){
            throw new Exception("file path is null");
        }
        //获取文件的后缀名
        File f = new File(path);
        if(f.exists()){
            f.delete();
        }else {
            throw new Exception("file is not fount");
        }
        return path;
    }



    /**
     * 获得指定文件的byte数组
     */

    public static byte[] getBytes(String filePath) throws Exception{
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        if(fis!=null){
            fis.close();
        }
        if(bos!=null){
            bos.close();
        }
        buffer = bos.toByteArray();
        return buffer;
    }


    public static void main(String arg[]) throws Exception{
        deleteFile("/Users/youkun/workProject/upload/1a6214d0-15aa-4d50-9fc4-39463e869918.jpg");
    }
}
